import { useState, useEffect } from 'react';
import PageHeader from '../components/PageHeader';
import IssueItem from '../components/IssueItem';
import { getIssueByPage } from '../api/issue';
import { List } from 'antd';
import { getTypeList } from '../redux/typeSlice';
import { useSelector, useDispatch } from 'react-redux';
import TypeSelect from '../components/TypeSelect';
import AddIssueButton from '../components/AddIssueButton';
import Recommend from '../components/Recommend';
import ScoreRanks from '../components/ScoreRanks';

function Issues() {
  const [issueInfo, setIssueInfo] = useState([]);
  const [searchParams, setSearchParams] = useState({ current: 1, pageSize: 5, total: 0 });

  const dispatch = useDispatch();
  const { typeList } = useSelector((state) => state.type);

  useEffect(() => {
    if (typeList.length === 0) {
      dispatch(getTypeList());
    }

    async function fetchData() {
      const { data } = await getIssueByPage(searchParams);
      setIssueInfo(data.data);
      setSearchParams({
        current: data.currentPage,
        pageSize: data.eachPage,
        total: data.count,
      });
    }
    fetchData();
  }, [searchParams.current, searchParams.pageSize]);

  function handlePageChange(current, pageSize) {
    setSearchParams({
      current,
      pageSize,
    });
  }

  return (
    <div className="">
      <PageHeader title="问题列表">
        <TypeSelect />
      </PageHeader>
      <div className="flex px-6">
        <div className="w-10/12">
          <List
            itemLayout="vertical"
            size="large"
            pagination={{
              ...searchParams,
              onChange: handlePageChange,
            }}
            dataSource={issueInfo}
            renderItem={(item) => (
              <List.Item key={item.issueTitle}>
                <IssueItem issueInfo={item} />
              </List.Item>
            )}
          />
        </div>

        <div className="w-4/12 px-3">
          <div className="pb-4">
            <AddIssueButton />
          </div>
          <div className="">
            <Recommend />
          </div>
          <div className="mt-3">
            <ScoreRanks />
          </div>
        </div>
      </div>
    </div>
  );
}

export default Issues;
